package com.jxmcloud.business.cut.service.impl.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jxmcloud.business.cut.json.DataConfigService;
import com.jxmcloud.business.cut.mapper.database.IRefreshConfigLogDBMapper;
import com.jxmcloud.business.cut.mapper.database.IUserActivityInfoDBMapper;
import com.jxmcloud.business.cut.mapper.database.IUserFlowInfoDBMapper;
import com.jxmcloud.business.cut.mapper.database.IUserLoginInfoDBMapper;
import com.jxmcloud.business.cut.model.database.*;
import com.jxmcloud.business.cut.service.app.system.ISystemService;
import com.jxmcloud.business.cut.service.database.*;
import com.xlcloud.platform.api.exception.BusinessException;
import com.xxl.sso.core.login.SsoTokenLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Service
@Slf4j
public class SystemServiceImpl implements ISystemService {
    @Autowired
    private DataConfigService dataConfigService;
    @Autowired
    private IUserFlowInfoDBMapper userFlowInfoDBMapper;
    @Autowired
    private IUserActivityInfoDBMapper userActivityInfoDBMapper;
    @Autowired
    private IUserLoginInfoDBMapper userLoginInfoDBMapper;
    @Autowired
    private IGiftBuyRecordDBService giftBuyRecordDBService;
    @Autowired
    private ILogItemDBService logItemDBService;
    @Autowired
    private IUserAwardInfoDBService userAwardInfoDBService;
    @Autowired
    private IUserBagDBService userBagDBService;
    @Autowired
    private IUserInviteSuccessDBService userInviteSuccessDBService;
    @Autowired
    private IUserTurntableDBService userTurntableDBService;
    @Autowired
    private IUserWatchLiveTaskDetailDBService userWatchLiveTaskDetailDBService;
    @Autowired
    private IUserProgressLogDBService userProgressLogDBService;
    @Resource
    private IRefreshConfigLogDBMapper refreshConfigLogDBMapper;

    @Override
    public void reloadServiceConfig() {
        // 记录用户操作记录
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attr.getRequest();
        XxlSsoUser xxlUser = SsoTokenLoginHelper.loginCheck(request.getHeader("xxl_sso_sessionid"));
        if(xxlUser == null){
            throw new BusinessException("登录超时，请重新登录");
        }
        try {
            // 重新加载配置
            dataConfigService.reloadConfig();

            // 记录日志
            recordOperationLog(xxlUser,0);
        } catch (Exception e) {
            // 记录日志
            recordOperationLog(xxlUser,1);
            log.error("配置加载失败:{}", e.getMessage());
            throw new BusinessException("配置加载失败");
        }

    }

    private void recordOperationLog(XxlSsoUser xxlUser, Integer status) {
        DBRefreshConfigLog data = new DBRefreshConfigLog();
        data.setRefreshTime(new Date());
        data.setStatus(status);
        data.setOperateName(xxlUser.getUsername());
        data.setOperateId(xxlUser.getUserid());
        refreshConfigLogDBMapper.insert(data);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void clearUserActivity(Long account) {
        DBUserLoginInfo dbUserLoginInfo = userLoginInfoDBMapper.selectOne(new QueryWrapper<DBUserLoginInfo>().eq("account", account));
        if(dbUserLoginInfo == null) {
            throw new BusinessException("用户不存在");
        }

        // 清空用户数据
        boolean flag = userLoginInfoDBMapper.delete(new QueryWrapper<DBUserLoginInfo>().eq("account", account)) > 0;
        if(!flag) {
            log.error("用户数据不存在，account:{}", account);
        }

        // 清空用户活动数据
        flag = userActivityInfoDBMapper.delete(new QueryWrapper<DBUserActivityInfo>().eq("uid", dbUserLoginInfo.getUid())) > 0;
        if(!flag) {
            log.error("用户活动数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户流程数据
        flag = userFlowInfoDBMapper.delete(new QueryWrapper<DBUserFlowInfo>().eq("uid", dbUserLoginInfo.getUid())) > 0;
        if(!flag) {
            log.error("用户流程数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户购买加速礼包数据
        flag = giftBuyRecordDBService.deleteData(dbUserLoginInfo.getUid());
        if(!flag) {
            log.error("用户购买加速礼包数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户道具日志数据
        flag = logItemDBService.remove(new QueryWrapper<DBLogItem>().eq("uid", dbUserLoginInfo.getUid()));
        if(!flag) {
            log.error("用户道具日志数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }
        // 清空用户奖励数据
        flag = userAwardInfoDBService.deleteData(dbUserLoginInfo.getUid());
        if (!flag) {
            log.error("用户奖励数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户背包数据
        flag = userBagDBService.remove(new QueryWrapper<DBUserBag>().eq("uid", dbUserLoginInfo.getUid()));
        if (!flag) {
            log.error("用户背包数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }
        // 清空用户邀请成功数据
        flag = userInviteSuccessDBService.remove(new QueryWrapper<DBUserInviteSuccess>().eq("uid", dbUserLoginInfo.getUid()));
        if (!flag) {
            log.error("用户邀请成功数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户转盘数据
        flag = userTurntableDBService.remove(new QueryWrapper<DBUserTurntable>().eq("uid", dbUserLoginInfo.getUid()));
        if (!flag) {
            log.error("用户转盘数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }

        // 清空用户观看直播任务数据
        flag = userWatchLiveTaskDetailDBService.remove(new QueryWrapper<DBUserWatchLiveTaskDetail>().eq("uid", dbUserLoginInfo.getUid()));
        if (!flag) {
            log.error("用户观看直播任务数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }
        flag = userProgressLogDBService.remove(new QueryWrapper<DBUserProgressLog>().eq("uid", dbUserLoginInfo.getUid()));
        if (!flag) {
            log.error("用户流程日志表数据不存在，uid:{}", dbUserLoginInfo.getUid());
        }
    }
}
